<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Token;
use app\common\model\Merchant as MerchantModel;
use app\common\model\Order;
use Exception;
use think\Db;

/**
 * 渠道分销商接口
 */
class Distributor extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token=Token::get($token);
        if($token["type"]!=4) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
        /*判断当前账号身份 end*/
        $user = \app\common\model\Distributor::get($this->auth->id);
        if(empty($user)) $this->error("渠道分销商不存在");
        if(empty($user["status"])) $this->error("渠道分销商审核中");
        if($user["status"]==2) $this->error("渠道分销商已被驳回：".$user["remark"]);
        if($user["status"]==3) $this->error("渠道分销商已被禁用");
    }

    /**
     * 修改资料
     * */
    public function distributorUpdate()
    {
        if(!$this->request->param("name")) $this->error("请填写分销商名称");
        $params = $this->request->param();
        //if (empty($params)) $this->error("没有任何修改");
        $row=\app\common\model\Distributor::get($this->auth->id);
        if(empty($row)) $this->error("渠道分销商不存在");
        Db::startTrans();
        try {
            $ret=$row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success(__('修改成功'));
        } else {
            $this->error("修改失败".$this->auth->getError());
        }
    }
    /**
     * 获取推广码
     * */
    public function getPromotionCode()
    {
        $user=$this->auth->getUser();
        $code=[
            "promotion_code"=>$user["promotion_code"],
            "promotion_url"=>$user["promotion_url"],
            "promotion_share"=>$user["promotion_share"],
        ];
        if(empty($user["promotion_code"]) || empty($user["promotion_url"])){
            $mycardModel = new MerchantModel();
            $code=$mycardModel->getPromotionCode($this->auth->id,1);//生成二维码
        }
        if(empty($code["promotion_share"]) && !empty($code["promotion_code"])){
            $qrcode=new \addons\qrcode\controller\Index();
            $url=$qrcode->getPoster(["promotion_code"=>$code["promotion_code"],"id"=>$this->auth->id,"mobile"=>$user["mobile"]]);
            $code["promotion_share"]=$url;
        }
        $this->success("成功",$code);
    }

    /**
     *分销订单
     * */
    public function orderList()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $order = Order::field("id,name,agent_commission,price,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime,order_no")
            ->where(["status" => '1', "agent_id" => $this->auth->id,"agent_type"=>'4']);
        $order_sum = Order::field("id,name,agent_commission,price,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime,order_no")
            ->where(["status" => '1', "agent_id" => $this->auth->id,"agent_type"=>'4']);
        if ($this->request->param("day")) {
            $day = $this->request->param("day");
            $day_field = "today";
            if ($day == 2) $day_field = "month";
            if ($day == 3) $day_field = "year";
            $order = $order->whereTime("createtime", $day_field);
            $order_sum = $order_sum->whereTime("createtime", $day_field);
        } else {
            if ($this->request->param("start_time")) {
                $order = $order->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
                $order_sum = $order_sum->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
            }
        }
        $list=$order
            ->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])->toArray();
        $list["all_money"]=$order_sum->sum("agent_commission").'';
        $this->success("成功", $list);
    }
}
